<template>
    <div class="login-container">
        <div class="title-container">
            <h3 class="title"><span>淄博金融风控管理平台</span></h3>
        </div>
        <!-- 扫码登录 -->
        <div class="login_box">
            <div class="qrcode">
                <div class="loginType">
                    <span @click="cur=0" :class="{active:cur == 0}">APP扫码登录</span>
                    <span @click="cur=1" :class="{active:cur == 1}">用户激活</span>
                </div>
                <div v-show="cur == 0" class="mod">
                    <div id="qrcode" v-show="state === 1 ||state === 2" v-loading="loading"></div>
                    <div class="empty" v-show="state === 0"></div>
                    <div class="refresh" v-show="state === 2">
                        <i class="refresh_mask"></i>
                        <i class="el-icon-refresh refresh_icon" @click="getQRCodeIdApi"></i>
                    </div>
                    <div>
                        <p class="sub_title">{{ tip }}</p>
                        <p class="sub_desc">扫码登录，更易、更快、更安全</p>
                    </div>
                </div>
                <div v-show="cur == 1">
                    <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-show="showCard">
                        <el-form-item label="身份证" prop="sfz">
                            <el-input v-model="form.sfz" placeholder="请输入身份证号码" clearable></el-input>
                        </el-form-item>
                        <div class="dialog-footer">
                            <el-button type="primary" @click="submit" :loading="addSubmitLoading">获取邀请码</el-button>
                        </div>
                    </el-form>
                    <div class="userQrCode" v-show="!showCard">
                        <p>邀请码：{{caCode}}</p>
                        <div id="userqrcode"></div>
                    </div>
                </div>
                <!-- <el-button type="text" size="mini" @click="handelOpen">用户注册</el-button> -->
            </div>
        </div>   
        <!-- <el-dialog title="用户注册" custom-class="code-dialog" center  width="30%" :visible.sync="codeBox" :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-show="showCard">
                <el-form-item label="身份证号码" prop="sfz">
                    <el-input v-model="form.sfz" placeholder="请输入身份证号码" clearable></el-input>
                </el-form-item>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submit" :loading="addSubmitLoading">获取邀请码</el-button>
                </div>
            </el-form>
            <div class="userQrCode" v-show="!showCard">
                <p>邀请码：{{caCode}}</p>
                <div id="userqrcode"></div>
            </div>
        </el-dialog>  -->
    </div>
</template>

<script>
    import { caLogin,getErCode,getErCodeResult,addXml,cutXml,getCert,getUserCode } from '@/api/login.js'
    import QRCode from 'qrcodejs2'
    import { getAuth } from '@/utils/auth'
    export default {
        name: 'Login',
        data() {
            var verifyId = (rule, value, callback) => {
                if(!value){
                    return new Error('请输入身份证号码')
                }else{
                    const reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/
                    if (!reg.test(value)) {
                        return callback(new Error('请输入正确格式的身份证号码！'))
                    } else {
                        callback()
                    }
                }
            };
            return {
                cur:0,
                loading:true,
                state: 0, // 场景：0无登录码，1有登陆码，2登录码过期
                tip: '正在获取登录码，请稍等', // 提示
                imgURL: '', // 登录码路径
                qrCodeId: 0,//签名数据 id
                accountId: '', // 扫码登录的用户ID
                timeCount:undefined,
                redirect:undefined,
                cert:undefined,//证书
                codeBox:false,
                addSubmitLoading:false,
                showCard:true,
                caCode:'',
                form:{},
                rules:{
                    sfz: [
                        { required: true, message: '请输入身份证号码', trigger: 'blur' },
                        { validator:verifyId, trigger: 'blur' }
                    ],
                }
            }
        },
        created() {
            this.getQRCodeIdApi();
        },
        watch: {
            $route: {
                handler: function(route) {
                    const query = route.query
                    if (query) {
                        this.redirect = query.redirect
                    }
                },
                immediate: true
            }
        },
        methods: {
            getQRCodeIdApi () {
                console.log('开始获取')
                // 所有参数重置
                this.state = 0 // 场景为无二维码
                this.tip = '正在获取二维码，请稍等'
                this.loading = true
                
                clearInterval(this.timeCount)
                // 1. 获取二维码返回给PC端
                getCert().then(data=>{
                    this.cert = data.data;
                    let param = {cert:this.cert}
                    getErCode(param).then((res) => {
                        cutXml(res.data.data).then(response=>{
                            this.loading = false
                            //let cutData= JSON.parse(response.data)
                            let cutData= response.data.data
                            this.qrCodeId = cutData.data.signDataId
                            let windowWidth = document.documentElement.clientWidth
                            let width = 240 * (windowWidth/1920)
                            let qrcodeCreater = new QRCode('qrcode',{
                                width: width,
                                height: width,
                                text:cutData.data.qrCode
                            })
                            qrcodeCreater._el.title = "";
                            this.state = 1
                            this.tip = '请扫描二维码登录'
                            this.timeCount = setInterval(this.infoToken, 3000) // 开启每隔3S的轮询，向服务器请求口令信息
                        });
                    })
                })
            },
            infoToken () {
                // 轮询查询登录状态
                let params = {type:this.qrCodeId}
                addXml(params).then(res=>{
                    getCert().then(data=>{
                       let param = {signDataId:res.data.data,cert:data.data}
                        getErCodeResult(param).then((response) => {
                            cutXml(response.data.data).then(re=>{
                                //let cutData = JSON.parse(re.data)
                                let cutData = re.data.data
                                let status = cutData.data.jobStatus
                                this.accountId = cutData.data.msspId
                                
                                if (status === 'FINISH') {
                                    // 状态为登录成功
                                    clearInterval(this.timeCount) // 关闭轮询，溜了
                                    //登录跳转首页
                                    this.goLogin();
                                } else if (status === 'UNSIGN') {
                                    //状态为待扫码
                                    this.tip = '请扫描二维码登录'
                                }else if(status === 'EXPIRE'){
                                    //状态为登录过期
                                    clearInterval(this.timeCount)
                                    this.state = 2
                                    this.tip = '二维码已过期，请刷新二维码'
                                }else if(status === 'REVOKE'){
                                    //状态为登录撤销
                                    clearInterval(this.timeCount)
                                    this.state = 2
                                    this.tip = '扫码登录被撤销'
                                }else if(status === 'REFUSE'){
                                    //状态为登录拒绝
                                    clearInterval(this.timeCount)
                                    this.state = 2
                                    this.tip = '扫码登录被拒绝'
                                } 
                            })
                        }).catch((error) => {
                            console.log(error)
                        }) 
                    })
                    
                });
                
            },
            goLogin () {
                this.loading = true;
                caLogin({username:this.accountId}).then(res => {
                    if(res.status){
                        // 获取用户信息，并保存到vuex
                        localStorage.setItem("username",res.data.userName);
                        localStorage.setItem("loginType", 'caLogin');
                        this.$store.dispatch('user/login', {
                            token: res.data.token,
                            userType: res.data.userType,
                            roleId: res.data.roleId,
                            username:res.data.userName
                        });
                        // 获取按钮权限
                        this.$store.dispatch("user/getAllBtn",res.data.roleId).then(btnList=>{
                            localStorage.setItem('btnList',JSON.stringify(btnList));
                        });
                        this.$router.push({
                            path: '/manager/index',
                        });
                    }else{
                        this.$message.error(res.msg);
                    }
                }).catch((error) => {
                    console.log(error)
                })
            },
            //用户注册
            handelOpen(){
                this.showCard = true;
                this.form = {};
                this.addSubmitLoading = false;
                this.caCode = '';
                this.codeBox = true;
                this.$nextTick(()=>{
                    this.$refs['form'].clearValidate();
                    document.getElementById("userqrcode").innerHTML = "";
                })
            },
            //提交
            submit(){
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        let params = {type:this.form.sfz}
                        addXml(params).then(result=>{
                            getCert().then(data=>{
                                let param = {
                                    sfz:result.data.data,
                                    cert:data.data
                                }
                                this.addSubmitLoading = true;
                                getUserCode(param).then(res=>{
                                    this.addSubmitLoading = false;
                                    if(res.status){
                                        cutXml(res.data.data).then(response=>{
                                            this.showCard = false;
                                            this.caCode = response.data.data.data.code;
                                            let windowWidth = document.documentElement.clientWidth
                                            let width = 240 * (windowWidth/1920)
                                            let authCode = response.data.data.data.authCode;//JSON.parse(res.data.data.data.authCode)
                                            let qrcodeCreater = new QRCode('userqrcode',{
                                                width: width,
                                                height: width,
                                                correctLevel : 3,
                                                text:authCode//JSON.stringify(authCode)
                                            })
                                            qrcodeCreater._el.title = "";
                                        })
                                    }else{
                                        this.$message.error(res.msg);
                                    }
                                }).catch(err=>{
                                    this.$message({
                                        type:'error',
                                        showClose:true,
                                        duration:60000,
                                        message:err
                                    });
                                })
                            })
                        })
                    }
                });
                
            }
        },
        destroyed() {
            
        }
    }
</script>



<style lang="scss" scoped>
.login-container {
    min-height: 100%;
    width: 100%;
    //background-color: #222653;
    background: no-repeat url('../../assets/login.jpg');
    background-size: 100% 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    overflow: hidden;
}
.title-container {
    position: absolute;
    top: 5%;
    left: 100px;
    .title {
        font-size: 40px;
        color: #fff;
        margin: 0px auto 10px auto;
        text-align: center;
        font-weight: bold;
    }
}
 /*登录框*/
.login_box {
  width: 500px;
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 190px;
  border-radius: 6px;
  box-shadow: 0 2px 10px #999;
}

/* .login_close {
  position: absolute;
  top: 0;
  right: 0;
  width: 64px;
  height: 64px;
  background: url(../assets/img/pcinput.png) no-repeat right top;
  background-size: 100% 100%;
  border-top-right-radius: 5px;
  cursor: pointer;
  z-index: 99;
} */

/*二维码*/
.qrcode {
  padding-top: 60px;
  width: 400px;
  height: 400px;
  position: relative;
  .mod{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
  .loginType{
    width: 100%;
    position: absolute;
    top:0;
    text-align: center;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    span{
        display: inline-block;
        width: 120px;
        height: 30px;
        line-height: 30px;
        font-size: 16px;
        font-weight: bold;
        &:hover{
            cursor: pointer;
        }
    }
    .active{
        color: #ff6600;
        box-shadow: 0 2px 0 #ff6600;
    }
  }
}
/* 二维码获取 */
.qrcode #qrcode{
  display: block;
  width: 240px;
  height: 240px;
}

.qrcode .sub_title {
  text-align: center;
  font-size: 16px;
  color: #353535;
  margin-bottom: 23px;
}

.qrcode .sub_desc {
  text-align: center;
  color: #a3a3a3;
  font-size: 14px;
  padding: 0 40px;
  line-height: 1.8;
}

/* 二维码为空 */
.qrcode .empty {
  display: block;
  width: 240px;
  height: 240px;
  background: #d7e8fc;
}

/* 二维码刷新 */
.qrcode .refresh {
  display: block;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 240px;
}

.qrcode .refresh .refresh_mask {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -120px;
  margin-top: -120px;
  width: 240px;
  height: 240px;
  background: #ffffffe0;
}

.qrcode .refresh .refresh_icon {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -48px;
  margin-top: -48px;
  height: 96px;
  width: 96px;
  cursor: pointer;
  //background: url(../assets/img/refresh.png) no-repeat;
}

/* .qrcode .refresh .refresh_icon:hover {
  animation: refresh 1s linear infinite;
}

@keyframes refresh {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
} */

/* 二维码结果 */
.qrcode .result {
  display: block;
  width: 240px;
  height: 240px;
  margin: 70px auto 25px;
}

.qrcode .result .u_avatar {
  height: 150px;
  width: 150px;
  margin-top: 15px;
  border-radius: 5px;
  box-shadow: 0 2px 10px #999;
  -moz-box-shadow: #999 0 2px 10px;
  -webkit-box-shadow: #999 0 2px 10px;
}

.qrcode .result .u_name {
  text-align: center;
  font-size: 19px;
  color: #353535;
  margin-top: 20px;
}
/deep/ .code-dialog{
    border-radius: 10px;
}
.userQrCode{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    #userqrcode{
        display: block;
        width: 240px;
        height: 240px;
    }
    p{
        font-size: 18px;
        font-weight: bold;
    }
}
.dialog-footer {
  text-align: center;margin: 20px auto;
}
</style>
